package com.ylsdxy.auth.translator;



import com.ylsdxy.auth.exception.CustomOauthException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

@Component
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        //认证方式异常
        if (e instanceof UnsupportedGrantTypeException) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new CustomOauthException("认证方式异常"));
        }
        //用户名或密码错误
        if (e instanceof InvalidGrantException) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new CustomOauthException("用户名或密码错误"));
        }

        return ResponseEntity
                .status(HttpStatus.UNAUTHORIZED)
                .body(new CustomOauthException("认证失败"));
    }
}
